package com.jxy.bean;

import com.jxy.bean.attribute.Attribute;
import com.jxy.bean.constant.ConstantPoolTag;
import com.jxy.bean.constant.Utf8Info;
import com.jxy.tool.Tool;

import java.io.DataInputStream;
import java.util.Arrays;

/**
 * 这是属性，不是常量中属性描述
 */
public class FieldInfo {
    private int access_flags;
    private int name_index;
    private int descriptor_index;
    private Attribute[] attributes;
    private ClassFile cf;

    public FieldInfo(DataInputStream dis, ClassFile cf) {
        access_flags = Tool.readU2(dis);
        name_index = Tool.readU2(dis);
        descriptor_index = Tool.readU2(dis);
        attributes = Tool.readAttribute(dis, cf);
        this.cf = cf;
    }

    public String getFieldName() {
        if (valid()) {
            Utf8Info utf8Info = (Utf8Info) cf.getPools()[name_index];
            return utf8Info.getString();
        }
        return "name_index err !";
    }

    public String getDescriptor() {
        if (valid()) {
            Utf8Info utf8Info = (Utf8Info) cf.getPools()[descriptor_index];
            return utf8Info.getString();
        }
        return "descriptor_index err !";
    }

    public boolean valid() {
        //name_index必须指向CONSTANT_Utf8_info结构
        if (cf.getPools()[name_index].getTag() != ConstantPoolTag.CONSTANT_Utf8.getTag()) {
            return false;
        }
        //descriptor_index必须指向CONSTANT_Utf8结构
        if (cf.getPools()[descriptor_index].getTag() != ConstantPoolTag.CONSTANT_Utf8.getTag()) {
            return false;
        }
        //TODO attributes 验证
        return true;
    }

    @Override
    public String toString() {
        return "FieldInfo{" +
                "access_flags=" + Integer.toHexString(access_flags) + "(" + Tool.analyAccessFlag(Tool.field_access_flags, access_flags) + ")" +
                ", name_index=" + name_index + "(" + getFieldName() +
                "), descriptor_index=" + descriptor_index + "(" + getDescriptor() +
                "), attributes=" + Arrays.toString(attributes) +
                '}';
    }
}
